package com.wj.hourupdate;

import java.util.ArrayList;
import java.util.List;

import com.google.gson.Gson;
import com.wj.connection.socket.ClientSocket;
import com.wj.connection.socket.ISocketConnection;
import com.wj.hourupdate.datasource.NewsData;
import com.wj.hourupdate.datasource.NewsDatasource;

import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.GridView;

public class MainActivity extends Activity implements Runnable {
	private ISocketConnection connect;
	private GridView gvNews;

	private NewsDatasource newsDatasource;
	private List<NewsData.News> newsDetailLst;
	private NewsListAdapter newsAdapter;
	
	private Handler handler;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		gvNews = (GridView) findViewById(R.id.gridView1);
		handler = new Handler();
		newsDatasource = 
				new NewsDatasource(MainActivity.this);
		
		readAllNews();
		new Thread(this).start();
	}

	public void onSettingClicked(final View v){
		Intent intent = new Intent(MainActivity.this, SettingActivity.class);
		MainActivity.this.startActivity(intent);
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	private void readAllNews(){
		newsDatasource.open();
		List<NewsData.News> newsLst = newsDatasource.listAllNews();
		newsDatasource.close();

		if(newsLst != null){
			newsDetailLst = new ArrayList<NewsData.News>();
			
			for(NewsData.News news : newsLst){
				newsDetailLst.add(news);
			}
			newsAdapter = new NewsListAdapter(MainActivity.this, newsDetailLst);
			gvNews.setAdapter(newsAdapter);
			gvNews.setSelection(newsDetailLst.size());
		}
	}
		
	private Runnable notifyAdapter = new Runnable(){

		@Override
		public void run() {
			
			newsDatasource.open();
			NewsData.News news = newsDatasource.listNews();
			newsDatasource.close();
			
			if(news != null){
				newsDetailLst.add(news);
	
				newsAdapter.notifyDataSetChanged();
				gvNews.smoothScrollToPosition(newsDetailLst.size());
				
				NotificationCompat.Builder mBuilder =
				        new NotificationCompat.Builder(MainActivity.this)
				        .setSmallIcon(R.drawable.ic_launcher)
				        .setContentTitle(news.getCdntitle())
				        .setContentText(news.getCdndesc());
				// Creates an explicit intent for an Activity in your app
				Intent resultIntent = new Intent(MainActivity.this, MainActivity.class);
	
				// The stack builder object will contain an artificial back stack for the
				// started Activity.
				// This ensures that navigating backward from the Activity leads out of
				// your application to the Home screen.
				TaskStackBuilder stackBuilder = TaskStackBuilder.create(MainActivity.this);
				// Adds the back stack for the Intent (but not the Intent itself)
				stackBuilder.addParentStack(MainActivity.class);
				// Adds the Intent that starts the Activity to the top of the stack
				stackBuilder.addNextIntent(resultIntent);
				PendingIntent resultPendingIntent =
				        stackBuilder.getPendingIntent(
				            0,
				            PendingIntent.FLAG_UPDATE_CURRENT
				        );
				mBuilder.setContentIntent(resultPendingIntent);
				NotificationManager mNotificationManager =
				    (NotificationManager) getSystemService(MainActivity.this.NOTIFICATION_SERVICE);
				// mId allows you to update the notification later on.
				mNotificationManager.notify(Integer.parseInt(news.getCdnid()), mBuilder.build());
			}
		}
	
	};

	@Override
	public void run() {
		try {
			connect = new ClientSocket(GlobalVar.IP, Integer.parseInt(GlobalVar.PORT));
			String msg;
			while ((msg = connect.receive()) != null) {
				Log.d("msg", msg);
				Gson gson = new Gson();
				NewsData newsDetail = gson
						.fromJson(msg, NewsData.class);
				
				newsDatasource.open();
				newsDatasource.insertNews(newsDetail);
				newsDatasource.close();
				handler.post(notifyAdapter);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
